import { Button, message, Form } from 'antd';
import React, { useState, useEffect, useRef, useImperativeHandle, forwardRef } from 'react';
import ProForm, { ModalForm, ProFormText } from '@ant-design/pro-form';
import { Input, FormInstance } from 'antd';
import { getPatientHospitalizationInfo, getPatientList, getDischargeStatus } from '@/services/order/api';
import ProTable from '@ant-design/pro-table';
import { isNull, showMsg, MsgType } from '@/utils/utils';
import './index.less';
import moment from 'moment';

const { Search } = Input;

interface MyProps {
  type: string; // 区分一次性订单 还是住院单
  onSubmit: Function;
  caseNoKey: string; // 查询病案号的方式，case_no/out_case_no
  changePatient?: Function; // 更换患者回调
  onChoice?: Function; // 选择住院号回调
  showMore?: Boolean; // 是否显示多条住院号
  fromTo?: string; // 来自哪个页面的
}
const GoodName: React.FC<MyProps> = forwardRef((props, ref) => {
  const { type, caseNoKey, changePatient, onChoice, showMore, fromTo } = props;
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [patientInfo, setPatientInfo] = useState<ORDERAPI.PatientHospitalInfo>({});
  const formRef = useRef<FormInstance>();
  const [caseList, setCaseList] = useState([]);
  const [selectedRow, setSelectedRow] = useState<STOCKGOODSAPI.GoodsItem>([]);
  const [showTable, setShowTable] = useState(false);
  const [inputNo, setInputNo] = useState('');

  // 暴露的子组件方法，给父组件调用
  useImperativeHandle(ref, () => ({
    clear: () => {
      setPatientInfo({});
      formRef.current?.resetFields();
    },
    update: (e) => {
      setPatientInfo(e);
    }
  }))

  const columns: ProColumns<WorkerServiceItem>[] = [
    {
      title: '住院号',
      dataIndex: 'visit_no',
      search: false,
      width: 60,
    },
    {
      title: '住院记录',
      dataIndex: 'is_in',
      search: false,
      width: 100,
      render: (val, record) => {
        if (val === 'Y') {
          return '住院中'
        }
        const cy = (record.discharge_time || '').substring(0, 8);
        return `${isNull(cy) ? '已' : moment(cy).format('YYYY-MM-DD')}出院`
      }
    },
  ]

  // 根据身份证查询患者信息
  const fetchPatientBySfz = async (data: { identity_no?: string;}, flag) => {
    try {
      const list = await getPatientList(data);

      if(!list.length) {
        showMsg('患者信息不存在!', MsgType.ERROR);
        return;
      }
      if (fromTo === 'onceOrder') {
        onChoice?.(list[0]);
        setPatientInfo(list[0]);
      }
      // if (type === 'zy') {
        // await fetchPatientByCaseNo(res.case_no);
      // }
    } catch (error) {
      console.log('error', error)
      showMsg(error?.data?.errmsg); 
    }
  }

  // 患者住院号查询
  const fetchPatientByCaseNo = async (input_no: string) => {
    try {
      setCaseList([]);
      setLoading(true);
      const data: ORDERAPI.PatientHospitalInfo[] = await getPatientHospitalizationInfo({[caseNoKey]: input_no});
      setLoading(false);
      let info: ORDERAPI.PatientHospitalInfo = {};

      if (Array.isArray(data) && data.length > 0) {
        if (showMore && data.length > 1) {
          // showMsg('检测到有多条住院记录，请选择', 'info');
          setCaseList(Object.assign([], data));
        } else {
          info = data[0];
          setPatientInfo(info);
          onChoice?.(info);
          setInputNo(info.visit_no)
        }
      } else {
        showMsg('未找到患者信息', MsgType.INFO);
        formRef.current?.setFieldsValue({
          patient_name: null,
          address: null
        });
      }
    } catch (error) {
      console.log('error', error);
      showMsg(error?.data?.errmsg);
    }
  }

  // 选择住院号
  const choiceZyh = () => {
    console.log('selectedRow', selectedRow);
    if (isNull(selectedRow)) {
      showMsg('请选择住院号');
      return;
    }
    setPatientInfo(selectedRow);
    onChoice?.(selectedRow);
    setInputNo(selectedRow.visit_no);
    setCaseList([]);
    document.getElementById('root').scrollTo(0, 0)
  }
  const forFormSearch = async(e) => {
    e.stopPropagation()
    console.log('forFormSearch', inputNo)
    // 就诊卡号
    if (inputNo.length > 10 && inputNo.length < 15) {
      await fetchPatientBySfz({ ic_card_no: inputNo }, true);
    } else if (inputNo.length === 15 || inputNo.length === 18) { // 身份证
      await fetchPatientBySfz({ identity_no: inputNo });
    } else if (inputNo.length > 4 && inputNo.length < 12) {
      await fetchPatientByCaseNo(inputNo);
    }
  }

  return (
    <div className="patient-form">
      <div className="searchInput">
        <Input
          name="input_no"
          value={inputNo}
          onPressEnter={(e) => {
            // 为病案号的时候，不可以敲回车执行表单
            if (inputNo.length > 4 && inputNo.length < 12 && Number.isFinite(parseFloat(inputNo))) {
              e.preventDefault();
              forFormSearch(e);
            }
          }}
          onChange={(e) => {
            const val = e.target.value;
            // 为病案号时
            setInputNo(val)
            if (!isNull(caseList) && val !== caseList[0].case_no) {
              setCaseList([]);
            }
            if (inputNo.length > 4 && inputNo.length < 12 && Number.isFinite(parseFloat(inputNo))) {

            } else {
              // onChoice?.({ visit_no: val });
            }
            onChoice?.({ visit_no: val });
          }}
          className="mySearch_comm"
          style={{ width: '100%' }}
          placeholder="输入完整身份证/病案号/住院号"
        />
        {(inputNo.length > 4 && inputNo.length < 12 && Number.isFinite(parseFloat(inputNo))) && (
          <Button loading={loading} onClick={forFormSearch} type="primary">
            检索住院号
          </Button>
        )}
      </div>
      {!isNull(caseList) && (
        <div className="tableBox">
          <ProTable
            rowKey="visit_no"
            // actionRef={actionRef}
            bordered
            className="worker-pro-table"
            formRef={formRef}
            manualRequest={true}
            rowSelection={{
              type: 'radio',
              columnWidth: 30,
              onChange: (selectedKeys, selectRowss) => {
                console.log('selectedRows111', selectRowss)
                const row = selectRowss[0];
                setSelectedRow(row);
              },
            }}
            scroll={{ y: caseList.length > 15 ? 390 : null }}
            dataSource={caseList}
            search={false}
            options={false}
            toolBarRender={false}
            columns={columns}
            pagination={false}
            footer={() => (
              <div style={{ textAlign: 'right' }}>
                <Button type="primary" onClick={choiceZyh}>
                  确定
                </Button>
              </div>
            )}
          />
        </div>
      )}
    </div>
  );
});

export default GoodName;